5 * Created on Sep 4, 2006
7 * Copyright © 2006 Yuri Astrakhan "<Firstname><Lastname>@gmail.com"
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
19 * You should have received a copy of the GNU General Public License along
20 * with this program; if not, write to the Free Software Foundation, Inc.,
21 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
22 * http://www.gnu.org/copyleft/gpl.html
29 * This is the main API class, used for both external and internal processing.
30 * When executed, it will create the requested formatter object,
31 * instantiate and execute an object associated with the needed action,
32 * and use formatter to print results.
33 * In case of an exception, an error message will be printed using the same formatter.
35 * To use API from another application, run it using FauxRequest object, in which
36 * case any internal exceptions will not be handled but passed up to the caller.
37 * After successful execution, use getResult() for the resulting data.
41 class ApiMain
extends ApiBase
{
43 * When no format parameter is given, this format will be used
45 const API_DEFAULT_FORMAT
= 'jsonfm';
48 * List of available modules: action name => module class
50 private static $Modules = array(
51 'login' => 'ApiLogin',
52 'logout' => 'ApiLogout',
53 'createaccount' => 'ApiCreateAccount',
54 'query' => 'ApiQuery',
55 'expandtemplates' => 'ApiExpandTemplates',
56 'parse' => 'ApiParse',
57 'stashedit' => 'ApiStashEdit',
58 'opensearch' => 'ApiOpenSearch',
59 'feedcontributions' => 'ApiFeedContributions',
60 'feedrecentchanges' => 'ApiFeedRecentChanges',
61 'feedwatchlist' => 'ApiFeedWatchlist',
63 'paraminfo' => 'ApiParamInfo',
65 'compare' => 'ApiComparePages',
66 'tokens' => 'ApiTokens',
69 'purge' => 'ApiPurge',
70 'setnotificationtimestamp' => 'ApiSetNotificationTimestamp',
71 'rollback' => 'ApiRollback',
72 'delete' => 'ApiDelete',
73 'undelete' => 'ApiUndelete',
74 'protect' => 'ApiProtect',
75 'block' => 'ApiBlock',
76 'unblock' => 'ApiUnblock',
78 'edit' => 'ApiEditPage',
79 'upload' => 'ApiUpload',
80 'filerevert' => 'ApiFileRevert',
81 'emailuser' => 'ApiEmailUser',
82 'watch' => 'ApiWatch',
83 'patrol' => 'ApiPatrol',
84 'import' => 'ApiImport',
85 'clearhasmsg' => 'ApiClearHasMsg',
86 'userrights' => 'ApiUserrights',
87 'options' => 'ApiOptions',
88 'imagerotate' => 'ApiImageRotate',
89 'revisiondelete' => 'ApiRevisionDelete',
93 * List of available formats: format name => format class
95 private static $Formats = array(
96 'json' => 'ApiFormatJson',
97 'jsonfm' => 'ApiFormatJson',
98 'php' => 'ApiFormatPhp',
99 'phpfm' => 'ApiFormatPhp',
100 'wddx' => 'ApiFormatWddx',
101 'wddxfm' => 'ApiFormatWddx',
102 'xml' => 'ApiFormatXml',
103 'xmlfm' => 'ApiFormatXml',
104 'yaml' => 'ApiFormatYaml',
105 'yamlfm' => 'ApiFormatYaml',
106 'rawfm' => 'ApiFormatJson',
107 'txt' => 'ApiFormatTxt',
108 'txtfm' => 'ApiFormatTxt',
109 'dbg' => 'ApiFormatDbg',
110 'dbgfm' => 'ApiFormatDbg',
111 'dump' => 'ApiFormatDump',
112 'dumpfm' => 'ApiFormatDump',
113 'none' => 'ApiFormatNone',
116 // @codingStandardsIgnoreStart String contenation on "msg" not allowed to break long line
118 * List of user roles that are specifically relevant to the API.
119 * array( 'right' => array ( 'msg' => 'Some message with a $1',
120 * 'params' => array ( $someVarToSubst ) ),
123 private static $mRights = array(
125 'msg' => 'right-writeapi',
128 'apihighlimits' => array(
129 'msg' => 'api-help-right-apihighlimits',
130 'params' => array( ApiBase
::LIMIT_SML2
, ApiBase
::LIMIT_BIG2
)
133 // @codingStandardsIgnoreEnd
140 private $mModuleMgr, $mResult;
142 private $mEnableWrite;
143 private $mInternalMode, $mSquidMaxage, $mModule;
145 private $mCacheMode = 'private';
146 private $mCacheControl = array();
147 private $mParamsUsed = array();
150 * Constructs an instance of ApiMain that utilizes the module and format specified by $request.
152 * @param IContextSource|WebRequest $context If this is an instance of
153 * FauxRequest, errors are thrown and no printing occurs
154 * @param bool $enableWrite Should be set to true if the api may modify data
156 public function __construct( $context = null, $enableWrite = false ) {
157 if ( $context === null ) {
158 $context = RequestContext
::getMain();
159 } elseif ( $context instanceof WebRequest
) {
162 $context = RequestContext
::getMain();
164 // We set a derivative context so we can change stuff later
165 $this->setContext( new DerivativeContext( $context ) );
167 if ( isset( $request ) ) {
168 $this->getContext()->setRequest( $request );
171 $this->mInternalMode
= ( $this->getRequest() instanceof FauxRequest
);
173 // Special handling for the main module: $parent === $this
174 parent
::__construct( $this, $this->mInternalMode ?
'main_int' : 'main' );
176 if ( !$this->mInternalMode
) {
177 // Impose module restrictions.
178 // If the current user cannot read,
179 // Remove all modules other than login
182 if ( $this->getVal( 'callback' ) !== null ) {
183 // JSON callback allows cross-site reads.
184 // For safety, strip user credentials.
185 wfDebug( "API: stripping user credentials for JSON callback\n" );
186 $wgUser = new User();
187 $this->getContext()->setUser( $wgUser );
191 $uselang = $this->getParameter( 'uselang' );
192 if ( $uselang === 'user' ) {
193 // Assume the parent context is going to return the user language
194 // for uselang=user (see T85635).
196 if ( $uselang === 'content' ) {
198 $uselang = $wgContLang->getCode();
200 $code = RequestContext
::sanitizeLangCode( $uselang );
201 $this->getContext()->setLanguage( $code );
202 if ( !$this->mInternalMode
) {
204 $wgLang = $this->getContext()->getLanguage();
205 RequestContext
::getMain()->setLanguage( $wgLang );
209 $config = $this->getConfig();
210 $this->mModuleMgr
= new ApiModuleManager( $this );
211 $this->mModuleMgr
->addModules( self
::$Modules, 'action' );
212 $this->mModuleMgr
->addModules( $config->get( 'APIModules' ), 'action' );
213 $this->mModuleMgr
->addModules( self
::$Formats, 'format' );
214 $this->mModuleMgr
->addModules( $config->get( 'APIFormatModules' ), 'format' );
216 $this->mResult
= new ApiResult( $this );
217 $this->mEnableWrite
= $enableWrite;
219 $this->mSquidMaxage
= -1; // flag for executeActionWithErrorHandling()
220 $this->mCommit
= false;
224 * Return true if the API was started by other PHP code using FauxRequest
227 public function isInternalMode() {
228 return $this->mInternalMode
;
232 * Get the ApiResult object associated with current request
236 public function getResult() {
237 return $this->mResult
;
241 * Get the API module object. Only works after executeAction()
245 public function getModule() {
246 return $this->mModule
;
250 * Get the result formatter object. Only works after setupExecuteAction()
252 * @return ApiFormatBase
254 public function getPrinter() {
255 return $this->mPrinter
;
259 * Set how long the response should be cached.
263 public function setCacheMaxAge( $maxage ) {
264 $this->setCacheControl( array(
265 'max-age' => $maxage,
266 's-maxage' => $maxage
271 * Set the type of caching headers which will be sent.
273 * @param string $mode One of:
274 * - 'public': Cache this object in public caches, if the maxage or smaxage
275 * parameter is set, or if setCacheMaxAge() was called. If a maximum age is
276 * not provided by any of these means, the object will be private.
277 * - 'private': Cache this object only in private client-side caches.
278 * - 'anon-public-user-private': Make this object cacheable for logged-out
279 * users, but private for logged-in users. IMPORTANT: If this is set, it must be
280 * set consistently for a given URL, it cannot be set differently depending on
281 * things like the contents of the database, or whether the user is logged in.
283 * If the wiki does not allow anonymous users to read it, the mode set here
284 * will be ignored, and private caching headers will always be sent. In other words,
285 * the "public" mode is equivalent to saying that the data sent is as public as a page
288 * For user-dependent data, the private mode should generally be used. The
289 * anon-public-user-private mode should only be used where there is a particularly
290 * good performance reason for caching the anonymous response, but where the
291 * response to logged-in users may differ, or may contain private data.
293 * If this function is never called, then the default will be the private mode.
295 public function setCacheMode( $mode ) {
296 if ( !in_array( $mode, array( 'private', 'public', 'anon-public-user-private' ) ) ) {
297 wfDebug( __METHOD__
. ": unrecognised cache mode \"$mode\"\n" );
299 // Ignore for forwards-compatibility
303 if ( !User
::isEveryoneAllowed( 'read' ) ) {
304 // Private wiki, only private headers
305 if ( $mode !== 'private' ) {
306 wfDebug( __METHOD__
. ": ignoring request for $mode cache mode, private wiki\n" );
312 if ( $mode === 'public' && $this->getParameter( 'uselang' ) === 'user' ) {
313 // User language is used for i18n, so we don't want to publicly
314 // cache. Anons are ok, because if they have non-default language
315 // then there's an appropriate Vary header set by whatever set
316 // their non-default language.
317 wfDebug( __METHOD__
. ": downgrading cache mode 'public' to " .
318 "'anon-public-user-private' due to uselang=user\n" );
319 $mode = 'anon-public-user-private';
322 wfDebug( __METHOD__
. ": setting cache mode $mode\n" );
323 $this->mCacheMode
= $mode;
327 * Set directives (key/value pairs) for the Cache-Control header.
328 * Boolean values will be formatted as such, by including or omitting
329 * without an equals sign.
331 * Cache control values set here will only be used if the cache mode is not
332 * private, see setCacheMode().
334 * @param array $directives
336 public function setCacheControl( $directives ) {
337 $this->mCacheControl
= $directives +
$this->mCacheControl
;
341 * Create an instance of an output formatter by its name
343 * @param string $format
345 * @return ApiFormatBase
347 public function createPrinterByName( $format ) {
348 $printer = $this->mModuleMgr
->getModule( $format, 'format' );
349 if ( $printer === null ) {
350 $this->dieUsage( "Unrecognized format: {$format}", 'unknown_format' );
357 * Execute api request. Any errors will be handled if the API was called by the remote client.
359 public function execute() {
361 if ( $this->mInternalMode
) {
362 $this->executeAction();
364 $this->executeActionWithErrorHandling();
371 * Execute an action, and in case of an error, erase whatever partial results
372 * have been accumulated, and replace it with an error message and a help screen.
374 protected function executeActionWithErrorHandling() {
375 // Verify the CORS header before executing the action
376 if ( !$this->handleCORS() ) {
377 // handleCORS() has sent a 403, abort
381 // Exit here if the request method was OPTIONS
382 // (assume there will be a followup GET or POST)
383 if ( $this->getRequest()->getMethod() === 'OPTIONS' ) {
387 // In case an error occurs during data output,
388 // clear the output buffer and print just the error information
391 $t = microtime( true );
393 $this->executeAction();
394 } catch ( Exception
$e ) {
395 $this->handleException( $e );
398 // Log the request whether or not there was an error
399 $this->logRequest( microtime( true ) - $t );
401 // Send cache headers after any code which might generate an error, to
402 // avoid sending public cache headers for errors.
403 $this->sendCacheHeaders();
409 * Handle an exception as an API response
412 * @param Exception $e
414 protected function handleException( Exception
$e ) {
415 // Bug 63145: Rollback any open database transactions
416 if ( !( $e instanceof UsageException
) ) {
417 // UsageExceptions are intentional, so don't rollback if that's the case
418 MWExceptionHandler
::rollbackMasterChangesAndLog( $e );
421 // Allow extra cleanup and logging
422 Hooks
::run( 'ApiMain::onException', array( $this, $e ) );
425 if ( !( $e instanceof UsageException
) ) {
426 MWExceptionHandler
::logException( $e );
429 // Handle any kind of exception by outputting properly formatted error message.
430 // If this fails, an unhandled exception should be thrown so that global error
431 // handler will process and log it.
433 $errCode = $this->substituteResultWithError( $e );
435 // Error results should not be cached
436 $this->setCacheMode( 'private' );
438 $response = $this->getRequest()->response();
439 $headerStr = 'MediaWiki-API-Error: ' . $errCode;
440 if ( $e->getCode() === 0 ) {
441 $response->header( $headerStr );
443 $response->header( $headerStr, true, $e->getCode() );
446 // Reset and print just the error message
449 // If the error occurred during printing, do a printer->profileOut()
450 $this->mPrinter
->safeProfileOut();
451 $this->printResult( true );
455 * Handle an exception from the ApiBeforeMain hook.
457 * This tries to print the exception as an API response, to be more
458 * friendly to clients. If it fails, it will rethrow the exception.
461 * @param Exception $e
464 public static function handleApiBeforeMainException( Exception
$e ) {
468 $main = new self( RequestContext
::getMain(), false );
469 $main->handleException( $e );
470 } catch ( Exception
$e2 ) {
471 // Nope, even that didn't work. Punt.
475 // Log the request and reset cache headers
476 $main->logRequest( 0 );
477 $main->sendCacheHeaders();
483 * Check the &origin= query parameter against the Origin: HTTP header and respond appropriately.
485 * If no origin parameter is present, nothing happens.
486 * If an origin parameter is present but doesn't match the Origin header, a 403 status code
487 * is set and false is returned.
488 * If the parameter and the header do match, the header is checked against $wgCrossSiteAJAXdomains
489 * and $wgCrossSiteAJAXdomainExceptions, and if the origin qualifies, the appropriate CORS
491 * http://www.w3.org/TR/cors/#resource-requests
492 * http://www.w3.org/TR/cors/#resource-preflight-requests
494 * @return bool False if the caller should abort (403 case), true otherwise (all other cases)
496 protected function handleCORS() {
497 $originParam = $this->getParameter( 'origin' ); // defaults to null
498 if ( $originParam === null ) {
499 // No origin parameter, nothing to do
503 $request = $this->getRequest();
504 $response = $request->response();
506 // Origin: header is a space-separated list of origins, check all of them
507 $originHeader = $request->getHeader( 'Origin' );
508 if ( $originHeader === false ) {
511 $originHeader = trim( $originHeader );
512 $origins = preg_split( '/\s+/', $originHeader );
515 if ( !in_array( $originParam, $origins ) ) {
516 // origin parameter set but incorrect
517 // Send a 403 response
518 $message = HttpStatus
::getMessage( 403 );
519 $response->header( "HTTP/1.1 403 $message", true, 403 );
520 $response->header( 'Cache-Control: no-cache' );
521 echo "'origin' parameter does not match Origin header\n";
526 $config = $this->getConfig();
527 $matchOrigin = count( $origins ) === 1 && self
::matchOrigin(
529 $config->get( 'CrossSiteAJAXdomains' ),
530 $config->get( 'CrossSiteAJAXdomainExceptions' )
533 if ( $matchOrigin ) {
534 $requestedMethod = $request->getHeader( 'Access-Control-Request-Method' );
535 $preflight = $request->getMethod() === 'OPTIONS' && $requestedMethod !== false;
537 // This is a CORS preflight request
538 if ( $requestedMethod !== 'POST' && $requestedMethod !== 'GET' ) {
539 // If method is not a case-sensitive match, do not set any additional headers and terminate.
542 // We allow the actual request to send the following headers
543 $requestedHeaders = $request->getHeader( 'Access-Control-Request-Headers' );
544 if ( $requestedHeaders !== false ) {
545 if ( !self
::matchRequestedHeaders( $requestedHeaders ) ) {
548 $response->header( 'Access-Control-Allow-Headers: ' . $requestedHeaders );
551 // We only allow the actual request to be GET or POST
552 $response->header( 'Access-Control-Allow-Methods: POST, GET' );
555 $response->header( "Access-Control-Allow-Origin: $originHeader" );
556 $response->header( 'Access-Control-Allow-Credentials: true' );
557 $response->header( "Timing-Allow-Origin: $originHeader" ); # http://www.w3.org/TR/resource-timing/#timing-allow-origin
560 $response->header( 'Access-Control-Expose-Headers: MediaWiki-API-Error, Retry-After, X-Database-Lag' );
564 $this->getOutput()->addVaryHeader( 'Origin' );
569 * Attempt to match an Origin header against a set of rules and a set of exceptions
570 * @param string $value Origin header
571 * @param array $rules Set of wildcard rules
572 * @param array $exceptions Set of wildcard rules
573 * @return bool True if $value matches a rule in $rules and doesn't match
574 * any rules in $exceptions, false otherwise
576 protected static function matchOrigin( $value, $rules, $exceptions ) {
577 foreach ( $rules as $rule ) {
578 if ( preg_match( self
::wildcardToRegex( $rule ), $value ) ) {
579 // Rule matches, check exceptions
580 foreach ( $exceptions as $exc ) {
581 if ( preg_match( self
::wildcardToRegex( $exc ), $value ) ) {
594 * Attempt to validate the value of Access-Control-Request-Headers against a list
595 * of headers that we allow the follow up request to send.
597 * @param string $requestedHeaders Comma seperated list of HTTP headers
598 * @return bool True if all requested headers are in the list of allowed headers
600 protected static function matchRequestedHeaders( $requestedHeaders ) {
601 if ( trim( $requestedHeaders ) === '' ) {
604 $requestedHeaders = explode( ',', $requestedHeaders );
605 $allowedAuthorHeaders = array_flip( array(
606 /* simple headers (see spec) */
611 /* non-authorable headers in XHR, which are however requested by some UAs */
615 /* MediaWiki whitelist */
618 foreach ( $requestedHeaders as $rHeader ) {
619 $rHeader = strtolower( trim( $rHeader ) );
620 if ( !isset( $allowedAuthorHeaders[$rHeader] ) ) {
621 wfDebugLog( 'api', 'CORS preflight failed on requested header: ' . $rHeader );
629 * Helper function to convert wildcard string into a regex
633 * @param string $wildcard String with wildcards
634 * @return string Regular expression
636 protected static function wildcardToRegex( $wildcard ) {
637 $wildcard = preg_quote( $wildcard, '/' );
638 $wildcard = str_replace(
644 return "/^https?:\/\/$wildcard$/";
647 protected function sendCacheHeaders() {
648 $response = $this->getRequest()->response();
649 $out = $this->getOutput();
651 $config = $this->getConfig();
653 if ( $config->get( 'VaryOnXFP' ) ) {
654 $out->addVaryHeader( 'X-Forwarded-Proto' );
657 if ( $this->mCacheMode
== 'private' ) {
658 $response->header( 'Cache-Control: private' );
662 $useXVO = $config->get( 'UseXVO' );
663 if ( $this->mCacheMode
== 'anon-public-user-private' ) {
664 $out->addVaryHeader( 'Cookie' );
665 $response->header( $out->getVaryHeader() );
667 $response->header( $out->getXVO() );
668 if ( $out->haveCacheVaryCookies() ) {
669 // Logged in, mark this request private
670 $response->header( 'Cache-Control: private' );
673 // Logged out, send normal public headers below
674 } elseif ( session_id() != '' ) {
675 // Logged in or otherwise has session (e.g. anonymous users who have edited)
676 // Mark request private
677 $response->header( 'Cache-Control: private' );
680 } // else no XVO and anonymous, send public headers below
683 // Send public headers
684 $response->header( $out->getVaryHeader() );
686 $response->header( $out->getXVO() );
689 // If nobody called setCacheMaxAge(), use the (s)maxage parameters
690 if ( !isset( $this->mCacheControl
['s-maxage'] ) ) {
691 $this->mCacheControl
['s-maxage'] = $this->getParameter( 'smaxage' );
693 if ( !isset( $this->mCacheControl
['max-age'] ) ) {
694 $this->mCacheControl
['max-age'] = $this->getParameter( 'maxage' );
697 if ( !$this->mCacheControl
['s-maxage'] && !$this->mCacheControl
['max-age'] ) {
698 // Public cache not requested
699 // Sending a Vary header in this case is harmless, and protects us
700 // against conditional calls of setCacheMaxAge().
701 $response->header( 'Cache-Control: private' );
706 $this->mCacheControl
['public'] = true;
708 // Send an Expires header
709 $maxAge = min( $this->mCacheControl
['s-maxage'], $this->mCacheControl
['max-age'] );
710 $expiryUnixTime = ( $maxAge == 0 ?
1 : time() +
$maxAge );
711 $response->header( 'Expires: ' . wfTimestamp( TS_RFC2822
, $expiryUnixTime ) );
713 // Construct the Cache-Control header
716 foreach ( $this->mCacheControl
as $name => $value ) {
717 if ( is_bool( $value ) ) {
719 $ccHeader .= $separator . $name;
723 $ccHeader .= $separator . "$name=$value";
728 $response->header( "Cache-Control: $ccHeader" );
732 * Replace the result data with the information about an exception.
733 * Returns the error code
734 * @param Exception $e
737 protected function substituteResultWithError( $e ) {
738 $result = $this->getResult();
740 // Printer may not be initialized if the extractRequestParams() fails for the main module
741 if ( !isset( $this->mPrinter
) ) {
742 // The printer has not been created yet. Try to manually get formatter value.
743 $value = $this->getRequest()->getVal( 'format', self
::API_DEFAULT_FORMAT
);
744 if ( !$this->mModuleMgr
->isDefined( $value, 'format' ) ) {
745 $value = self
::API_DEFAULT_FORMAT
;
748 $this->mPrinter
= $this->createPrinterByName( $value );
751 // Printer may not be able to handle errors. This is particularly
752 // likely if the module returns something for getCustomPrinter().
753 if ( !$this->mPrinter
->canPrintErrors() ) {
754 $this->mPrinter
->safeProfileOut();
755 $this->mPrinter
= $this->createPrinterByName( self
::API_DEFAULT_FORMAT
);
758 // Update raw mode flag for the selected printer.
759 $result->setRawMode( $this->mPrinter
->getNeedsRawData() );
761 $config = $this->getConfig();
763 if ( $e instanceof UsageException
) {
764 // User entered incorrect parameters - generate error response
765 $errMessage = $e->getMessageArray();
766 $link = wfExpandUrl( wfScript( 'api' ) );
767 ApiResult
::setContent( $errMessage, "See $link for API usage" );
769 // Something is seriously wrong
770 if ( ( $e instanceof DBQueryError
) && !$config->get( 'ShowSQLErrors' ) ) {
771 $info = 'Database query error';
773 $info = "Exception Caught: {$e->getMessage()}";
777 'code' => 'internal_api_error_' . get_class( $e ),
778 'info' => '[' . MWExceptionHandler
::getLogId( $e ) . '] ' . $info,
780 if ( $config->get( 'ShowExceptionDetails' ) ) {
781 ApiResult
::setContent(
783 MWExceptionHandler
::getRedactedTraceAsString( $e )
788 // Remember all the warnings to re-add them later
789 $oldResult = $result->getData();
790 $warnings = isset( $oldResult['warnings'] ) ?
$oldResult['warnings'] : null;
794 $requestid = $this->getParameter( 'requestid' );
795 if ( !is_null( $requestid ) ) {
796 $result->addValue( null, 'requestid', $requestid, ApiResult
::NO_SIZE_CHECK
);
798 if ( $config->get( 'ShowHostnames' ) ) {
799 // servedby is especially useful when debugging errors
800 $result->addValue( null, 'servedby', wfHostName(), ApiResult
::NO_SIZE_CHECK
);
802 if ( $warnings !== null ) {
803 $result->addValue( null, 'warnings', $warnings, ApiResult
::NO_SIZE_CHECK
);
806 $result->addValue( null, 'error', $errMessage, ApiResult
::NO_SIZE_CHECK
);
808 return $errMessage['code'];
812 * Set up for the execution.
815 protected function setupExecuteAction() {
816 // First add the id to the top element
817 $result = $this->getResult();
818 $requestid = $this->getParameter( 'requestid' );
819 if ( !is_null( $requestid ) ) {
820 $result->addValue( null, 'requestid', $requestid );
823 if ( $this->getConfig()->get( 'ShowHostnames' ) ) {
824 $servedby = $this->getParameter( 'servedby' );
826 $result->addValue( null, 'servedby', wfHostName() );
830 if ( $this->getParameter( 'curtimestamp' ) ) {
831 $result->addValue( null, 'curtimestamp', wfTimestamp( TS_ISO_8601
, time() ),
832 ApiResult
::NO_SIZE_CHECK
);
835 $params = $this->extractRequestParams();
837 $this->mAction
= $params['action'];
839 if ( !is_string( $this->mAction
) ) {
840 $this->dieUsage( 'The API requires a valid action parameter', 'unknown_action' );
847 * Set up the module for response
848 * @return ApiBase The module that will handle this action
849 * @throws MWException
850 * @throws UsageException
852 protected function setupModule() {
853 // Instantiate the module requested by the user
854 $module = $this->mModuleMgr
->getModule( $this->mAction
, 'action' );
855 if ( $module === null ) {
856 $this->dieUsage( 'The API requires a valid action parameter', 'unknown_action' );
858 $moduleParams = $module->extractRequestParams();
860 // Check token, if necessary
861 if ( $module->needsToken() === true ) {
862 throw new MWException(
863 "Module '{$module->getModuleName()}' must be updated for the new token handling. " .
864 "See documentation for ApiBase::needsToken for details."
867 if ( $module->needsToken() ) {
868 if ( !$module->mustBePosted() ) {
869 throw new MWException(
870 "Module '{$module->getModuleName()}' must require POST to use tokens."
874 if ( !isset( $moduleParams['token'] ) ) {
875 $this->dieUsageMsg( array( 'missingparam', 'token' ) );
878 if ( !$this->getConfig()->get( 'DebugAPI' ) &&
880 $module->encodeParamName( 'token' ),
881 $this->getRequest()->getQueryValues()
885 "The '{$module->encodeParamName( 'token' )}' parameter was found in the query string, but must be in the POST body",
890 if ( !$module->validateToken( $moduleParams['token'], $moduleParams ) ) {
891 $this->dieUsageMsg( 'sessionfailure' );
899 * Check the max lag if necessary
900 * @param ApiBase $module Api module being used
901 * @param array $params Array an array containing the request parameters.
902 * @return bool True on success, false should exit immediately
904 protected function checkMaxLag( $module, $params ) {
905 if ( $module->shouldCheckMaxlag() && isset( $params['maxlag'] ) ) {
907 $maxLag = $params['maxlag'];
908 list( $host, $lag ) = wfGetLB()->getMaxLag();
909 if ( $lag > $maxLag ) {
910 $response = $this->getRequest()->response();
912 $response->header( 'Retry-After: ' . max( intval( $maxLag ), 5 ) );
913 $response->header( 'X-Database-Lag: ' . intval( $lag ) );
915 if ( $this->getConfig()->get( 'ShowHostnames' ) ) {
916 $this->dieUsage( "Waiting for $host: $lag seconds lagged", 'maxlag' );
919 $this->dieUsage( "Waiting for a database server: $lag seconds lagged", 'maxlag' );
927 * Check for sufficient permissions to execute
928 * @param ApiBase $module An Api module
930 protected function checkExecutePermissions( $module ) {
931 $user = $this->getUser();
932 if ( $module->isReadMode() && !User
::isEveryoneAllowed( 'read' ) &&
933 !$user->isAllowed( 'read' )
935 $this->dieUsageMsg( 'readrequired' );
937 if ( $module->isWriteMode() ) {
938 if ( !$this->mEnableWrite
) {
939 $this->dieUsageMsg( 'writedisabled' );
941 if ( !$user->isAllowed( 'writeapi' ) ) {
942 $this->dieUsageMsg( 'writerequired' );
944 if ( wfReadOnly() ) {
945 $this->dieReadOnly();
949 // Allow extensions to stop execution for arbitrary reasons.
951 if ( !Hooks
::run( 'ApiCheckCanExecute', array( $module, $user, &$message ) ) ) {
952 $this->dieUsageMsg( $message );
957 * Check asserts of the user's rights
958 * @param array $params
960 protected function checkAsserts( $params ) {
961 if ( isset( $params['assert'] ) ) {
962 $user = $this->getUser();
963 switch ( $params['assert'] ) {
965 if ( $user->isAnon() ) {
966 $this->dieUsage( 'Assertion that the user is logged in failed', 'assertuserfailed' );
970 if ( !$user->isAllowed( 'bot' ) ) {
971 $this->dieUsage( 'Assertion that the user has the bot right failed', 'assertbotfailed' );
979 * Check POST for external response and setup result printer
980 * @param ApiBase $module An Api module
981 * @param array $params An array with the request parameters
983 protected function setupExternalResponse( $module, $params ) {
984 if ( !$this->getRequest()->wasPosted() && $module->mustBePosted() ) {
985 // Module requires POST. GET request might still be allowed
986 // if $wgDebugApi is true, otherwise fail.
987 $this->dieUsageMsgOrDebug( array( 'mustbeposted', $this->mAction
) );
990 // See if custom printer is used
991 $this->mPrinter
= $module->getCustomPrinter();
992 if ( is_null( $this->mPrinter
) ) {
993 // Create an appropriate printer
994 $this->mPrinter
= $this->createPrinterByName( $params['format'] );
997 if ( $this->mPrinter
->getNeedsRawData() ) {
998 $this->getResult()->setRawMode();
1003 * Execute the actual module, without any error handling
1005 protected function executeAction() {
1006 $params = $this->setupExecuteAction();
1007 $module = $this->setupModule();
1008 $this->mModule
= $module;
1010 $this->checkExecutePermissions( $module );
1012 if ( !$this->checkMaxLag( $module, $params ) ) {
1016 if ( !$this->mInternalMode
) {
1017 $this->setupExternalResponse( $module, $params );
1020 $this->checkAsserts( $params );
1023 $module->profileIn();
1025 Hooks
::run( 'APIAfterExecute', array( &$module ) );
1026 $module->profileOut();
1028 $this->reportUnusedParams();
1030 if ( !$this->mInternalMode
) {
1031 //append Debug information
1032 MWDebug
::appendDebugInfoToApiResult( $this->getContext(), $this->getResult() );
1034 // Print result data
1035 $this->printResult( false );
1040 * Log the preceding request
1041 * @param int $time Time in seconds
1043 protected function logRequest( $time ) {
1044 $request = $this->getRequest();
1045 $milliseconds = $time === null ?
'?' : round( $time * 1000 );
1047 ' ' . $request->getMethod() .
1048 ' ' . wfUrlencode( str_replace( ' ', '_', $this->getUser()->getName() ) ) .
1049 ' ' . $request->getIP() .
1050 ' T=' . $milliseconds . 'ms';
1051 foreach ( $this->getParamsUsed() as $name ) {
1052 $value = $request->getVal( $name );
1053 if ( $value === null ) {
1056 $s .= ' ' . $name . '=';
1057 if ( strlen( $value ) > 256 ) {
1058 $encValue = $this->encodeRequestLogValue( substr( $value, 0, 256 ) );
1059 $s .= $encValue . '[...]';
1061 $s .= $this->encodeRequestLogValue( $value );
1065 wfDebugLog( 'api', $s, 'private' );
1069 * Encode a value in a format suitable for a space-separated log line.
1073 protected function encodeRequestLogValue( $s ) {
1076 $chars = ';@$!*(),/:';
1077 $numChars = strlen( $chars );
1078 for ( $i = 0; $i < $numChars; $i++
) {
1079 $table[rawurlencode( $chars[$i] )] = $chars[$i];
1083 return strtr( rawurlencode( $s ), $table );
1087 * Get the request parameters used in the course of the preceding execute() request
1090 protected function getParamsUsed() {
1091 return array_keys( $this->mParamsUsed
);
1095 * Get a request value, and register the fact that it was used, for logging.
1096 * @param string $name
1097 * @param mixed $default
1100 public function getVal( $name, $default = null ) {
1101 $this->mParamsUsed
[$name] = true;
1103 $ret = $this->getRequest()->getVal( $name );
1104 if ( $ret === null ) {
1105 if ( $this->getRequest()->getArray( $name ) !== null ) {
1106 // See bug 10262 for why we don't just join( '|', ... ) the
1109 "Parameter '$name' uses unsupported PHP array syntax"
1118 * Get a boolean request value, and register the fact that the parameter
1119 * was used, for logging.
1120 * @param string $name
1123 public function getCheck( $name ) {
1124 return $this->getVal( $name, null ) !== null;
1128 * Get a request upload, and register the fact that it was used, for logging.
1131 * @param string $name Parameter name
1132 * @return WebRequestUpload
1134 public function getUpload( $name ) {
1135 $this->mParamsUsed
[$name] = true;
1137 return $this->getRequest()->getUpload( $name );
1141 * Report unused parameters, so the client gets a hint in case it gave us parameters we don't know,
1142 * for example in case of spelling mistakes or a missing 'g' prefix for generators.
1144 protected function reportUnusedParams() {
1145 $paramsUsed = $this->getParamsUsed();
1146 $allParams = $this->getRequest()->getValueNames();
1148 if ( !$this->mInternalMode
) {
1149 // Printer has not yet executed; don't warn that its parameters are unused
1150 $printerParams = array_map(
1151 array( $this->mPrinter
, 'encodeParamName' ),
1152 array_keys( $this->mPrinter
->getFinalParams() ?
: array() )
1154 $unusedParams = array_diff( $allParams, $paramsUsed, $printerParams );
1156 $unusedParams = array_diff( $allParams, $paramsUsed );
1159 if ( count( $unusedParams ) ) {
1160 $s = count( $unusedParams ) > 1 ?
's' : '';
1161 $this->setWarning( "Unrecognized parameter$s: '" . implode( $unusedParams, "', '" ) . "'" );
1166 * Print results using the current printer
1168 * @param bool $isError
1170 protected function printResult( $isError ) {
1171 if ( $this->getConfig()->get( 'DebugAPI' ) !== false ) {
1172 $this->setWarning( 'SECURITY WARNING: $wgDebugAPI is enabled' );
1175 $this->getResult()->cleanUpUTF8();
1176 $printer = $this->mPrinter
;
1177 $printer->profileIn();
1179 $printer->initPrinter( false );
1181 $printer->execute();
1182 $printer->closePrinter();
1183 $printer->profileOut();
1189 public function isReadMode() {
1194 * See ApiBase for description.
1198 public function getAllowedParams() {
1201 ApiBase
::PARAM_DFLT
=> 'help',
1202 ApiBase
::PARAM_TYPE
=> 'submodule',
1205 ApiBase
::PARAM_DFLT
=> ApiMain
::API_DEFAULT_FORMAT
,
1206 ApiBase
::PARAM_TYPE
=> 'submodule',
1209 ApiBase
::PARAM_TYPE
=> 'integer'
1212 ApiBase
::PARAM_TYPE
=> 'integer',
1213 ApiBase
::PARAM_DFLT
=> 0
1216 ApiBase
::PARAM_TYPE
=> 'integer',
1217 ApiBase
::PARAM_DFLT
=> 0
1220 ApiBase
::PARAM_TYPE
=> array( 'user', 'bot' )
1222 'requestid' => null,
1223 'servedby' => false,
1224 'curtimestamp' => false,
1227 ApiBase
::PARAM_DFLT
=> 'user',
1232 /** @see ApiBase::getExamplesMessages() */
1233 protected function getExamplesMessages() {
1236 => 'apihelp-help-example-main',
1237 'action=help&recursivesubmodules=1'
1238 => 'apihelp-help-example-recursive',
1242 public function modifyHelp( array &$help, array $options ) {
1243 // Wish PHP had an "array_insert_before". Instead, we have to manually
1244 // reindex the array to get 'permissions' in the right place.
1247 foreach ( $oldHelp as $k => $v ) {
1248 if ( $k === 'submodules' ) {
1249 $help['permissions'] = '';
1253 $help['credits'] = '';
1255 // Fill 'permissions'
1256 $help['permissions'] .= Html
::openElement( 'div',
1257 array( 'class' => 'apihelp-block apihelp-permissions' ) );
1258 $m = $this->msg( 'api-help-permissions' );
1259 if ( !$m->isDisabled() ) {
1260 $help['permissions'] .= Html
::rawElement( 'div', array( 'class' => 'apihelp-block-head' ),
1261 $m->numParams( count( self
::$mRights ) )->parse()
1264 $help['permissions'] .= Html
::openElement( 'dl' );
1265 foreach ( self
::$mRights as $right => $rightMsg ) {
1266 $help['permissions'] .= Html
::element( 'dt', null, $right );
1268 $rightMsg = $this->msg( $rightMsg['msg'], $rightMsg['params'] )->parse();
1269 $help['permissions'] .= Html
::rawElement( 'dd', null, $rightMsg );
1271 $groups = array_map( function ( $group ) {
1272 return $group == '*' ?
'all' : $group;
1273 }, User
::getGroupsWithPermission( $right ) );
1275 $help['permissions'] .= Html
::rawElement( 'dd', null,
1276 $this->msg( 'api-help-permissions-granted-to' )
1277 ->numParams( count( $groups ) )
1278 ->params( $this->getLanguage()->commaList( $groups ) )
1282 $help['permissions'] .= Html
::closeElement( 'dl' );
1283 $help['permissions'] .= Html
::closeElement( 'div' );
1285 // Fill 'credits', if applicable
1286 if ( empty( $options['nolead'] ) ) {
1287 $help['credits'] .= Html
::element( 'h' . min( 6, $options['headerlevel'] +
1 ),
1288 array( 'id' => '+credits', 'class' => 'apihelp-header' ),
1289 $this->msg( 'api-credits-header' )->parse()
1291 $help['credits'] .= $this->msg( 'api-credits' )->useDatabase( false )->parseAsBlock();
1295 private $mCanApiHighLimits = null;
1298 * Check whether the current user is allowed to use high limits
1301 public function canApiHighLimits() {
1302 if ( !isset( $this->mCanApiHighLimits
) ) {
1303 $this->mCanApiHighLimits
= $this->getUser()->isAllowed( 'apihighlimits' );
1306 return $this->mCanApiHighLimits
;
1310 * Overrides to return this instance's module manager.
1311 * @return ApiModuleManager
1313 public function getModuleManager() {
1314 return $this->mModuleMgr
;
1318 * Fetches the user agent used for this request
1320 * The value will be the combination of the 'Api-User-Agent' header (if
1321 * any) and the standard User-Agent header (if any).
1325 public function getUserAgent() {
1327 $this->getRequest()->getHeader( 'Api-user-agent' ) . ' ' .
1328 $this->getRequest()->getHeader( 'User-agent' )
1332 /************************************************************************//**
1338 * Sets whether the pretty-printer should format *bold* and $italics$
1340 * @deprecated since 1.25
1343 public function setHelp( $help = true ) {
1344 wfDeprecated( __METHOD__
, '1.25' );
1345 $this->mPrinter
->setHelp( $help );
1349 * Override the parent to generate help messages for all available modules.
1351 * @deprecated since 1.25
1354 public function makeHelpMsg() {
1355 wfDeprecated( __METHOD__
, '1.25' );
1358 // Get help text from cache if present
1359 $key = wfMemcKey( 'apihelp', $this->getModuleName(),
1360 str_replace( ' ', '_', SpecialVersion
::getVersion( 'nodb' ) ) );
1362 $cacheHelpTimeout = $this->getConfig()->get( 'APICacheHelpTimeout' );
1363 if ( $cacheHelpTimeout > 0 ) {
1364 $cached = $wgMemc->get( $key );
1369 $retval = $this->reallyMakeHelpMsg();
1370 if ( $cacheHelpTimeout > 0 ) {
1371 $wgMemc->set( $key, $retval, $cacheHelpTimeout );
1378 * @deprecated since 1.25
1379 * @return mixed|string
1381 public function reallyMakeHelpMsg() {
1382 wfDeprecated( __METHOD__
, '1.25' );
1385 // Use parent to make default message for the main module
1386 $msg = parent
::makeHelpMsg();
1388 $astriks = str_repeat( '*** ', 14 );
1389 $msg .= "\n\n$astriks Modules $astriks\n\n";
1391 foreach ( $this->mModuleMgr
->getNames( 'action' ) as $name ) {
1392 $module = $this->mModuleMgr
->getModule( $name );
1393 $msg .= self
::makeHelpMsgHeader( $module, 'action' );
1395 $msg2 = $module->makeHelpMsg();
1396 if ( $msg2 !== false ) {
1402 $msg .= "\n$astriks Permissions $astriks\n\n";
1403 foreach ( self
::$mRights as $right => $rightMsg ) {
1404 $rightsMsg = $this->msg( $rightMsg['msg'], $rightMsg['params'] )
1405 ->useDatabase( false )
1406 ->inLanguage( 'en' )
1408 $groups = User
::getGroupsWithPermission( $right );
1409 $msg .= "* " . $right . " *\n $rightsMsg" .
1410 "\nGranted to:\n " . str_replace( '*', 'all', implode( ', ', $groups ) ) . "\n\n";
1413 $msg .= "\n$astriks Formats $astriks\n\n";
1414 foreach ( $this->mModuleMgr
->getNames( 'format' ) as $name ) {
1415 $module = $this->mModuleMgr
->getModule( $name );
1416 $msg .= self
::makeHelpMsgHeader( $module, 'format' );
1417 $msg2 = $module->makeHelpMsg();
1418 if ( $msg2 !== false ) {
1424 $credits = $this->msg( 'api-credits' )->useDatabase( 'false' )->inLanguage( 'en' )->text();
1425 $credits = str_replace( "\n", "\n ", $credits );
1426 $msg .= "\n*** Credits: ***\n $credits\n";
1432 * @deprecated since 1.25
1433 * @param ApiBase $module
1434 * @param string $paramName What type of request is this? e.g. action,
1435 * query, list, prop, meta, format
1438 public static function makeHelpMsgHeader( $module, $paramName ) {
1439 wfDeprecated( __METHOD__
, '1.25' );
1440 $modulePrefix = $module->getModulePrefix();
1441 if ( strval( $modulePrefix ) !== '' ) {
1442 $modulePrefix = "($modulePrefix) ";
1445 return "* $paramName={$module->getModuleName()} $modulePrefix*";
1449 * Check whether the user wants us to show version information in the API help
1451 * @deprecated since 1.21, always returns false
1453 public function getShowVersions() {
1454 wfDeprecated( __METHOD__
, '1.21' );
1460 * Add or overwrite a module in this ApiMain instance. Intended for use by extending
1461 * classes who wish to add their own modules to their lexicon or override the
1462 * behavior of inherent ones.
1464 * @deprecated since 1.21, Use getModuleManager()->addModule() instead.
1465 * @param string $name The identifier for this module.
1466 * @param ApiBase $class The class where this module is implemented.
1468 protected function addModule( $name, $class ) {
1469 $this->getModuleManager()->addModule( $name, 'action', $class );
1473 * Add or overwrite an output format for this ApiMain. Intended for use by extending
1474 * classes who wish to add to or modify current formatters.
1476 * @deprecated since 1.21, Use getModuleManager()->addModule() instead.
1477 * @param string $name The identifier for this format.
1478 * @param ApiFormatBase $class The class implementing this format.
1480 protected function addFormat( $name, $class ) {
1481 $this->getModuleManager()->addModule( $name, 'format', $class );
1485 * Get the array mapping module names to class names
1486 * @deprecated since 1.21, Use getModuleManager()'s methods instead.
1489 function getModules() {
1490 return $this->getModuleManager()->getNamesWithClasses( 'action' );
1494 * Returns the list of supported formats in form ( 'format' => 'ClassName' )
1497 * @deprecated since 1.21, Use getModuleManager()'s methods instead.
1500 public function getFormats() {
1501 return $this->getModuleManager()->getNamesWithClasses( 'format' );
1509 * This exception will be thrown when dieUsage is called to stop module execution.
1513 class UsageException
extends MWException
{
1520 private $mExtraData;
1523 * @param string $message
1524 * @param string $codestr
1526 * @param array|null $extradata
1528 public function __construct( $message, $codestr, $code = 0, $extradata = null ) {
1529 parent
::__construct( $message, $code );
1530 $this->mCodestr
= $codestr;
1531 $this->mExtraData
= $extradata;
1537 public function getCodeString() {
1538 return $this->mCodestr
;
1544 public function getMessageArray() {
1546 'code' => $this->mCodestr
,
1547 'info' => $this->getMessage()
1549 if ( is_array( $this->mExtraData
) ) {
1550 $result = array_merge( $result, $this->mExtraData
);
1559 public function __toString() {
1560 return "{$this->getCodeString()}: {$this->getMessage()}";
1565 * For really cool vim folding this needs to be at the end:
1566 * vim: foldmarker=@{,@} foldmethod=marker